package net.zcy.springbootmybatis.controller;

import net.zcy.springbootmybatis.entity.UserEntity;
import net.zcy.springbootmybatis.exception.ResultException;
import net.zcy.springbootmybatis.mapper.UserMapper;
import net.zcy.springbootmybatis.output.Result;
import net.zcy.springbootmybatis.utils.ResultUtil;
import net.zcy.springbootmybatis.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping(value = "/getUsers")
    public Result getUsers(){

        List<UserEntity> listUserEntity = userMapper.getAll();

        return ResultUtil.success(listUserEntity);
    }

    @GetMapping(value = "/getUser")
    public Result getOne(Long id){

        UserEntity userEntity = userMapper.getOne(id);

        return ResultUtil.success(userEntity);
    }

    @PostMapping(value = "/addUser")
    public Result save(@Valid UserVo userVo , BindingResult bindingResult,UserEntity userEntity){
        if(bindingResult.hasErrors()){
            throw new ResultException(1,bindingResult.getFieldError().getDefaultMessage());
        }

        Integer userResult =  userMapper.insert(userEntity);

        return ResultUtil.success(userResult);
    }

    @PostMapping(value = "/updateUser")
    public Integer update(UserEntity userEntity){

        return userMapper.update(userEntity);
    }

    @PostMapping(value = "/deleteUser")
    public Integer delete(Long id){
        return userMapper.delete(id);
    }


}
